var config = {
    publicUrl: "http://localhost:3000/product/",
    cateUrl: "http://localhost:3000/cate/",
    commentUrl: "http://localhost:3000/comment/",
};


//初始化表格
$('#product').datagrid({
    url: `${config.publicUrl}list`,
    pagination: true,
    method: "post",
    fit: true,
    striped: true,
    nowrap: true,
    fitColumns: true,
    columns: [[
        { field: 'ck', checkbox: true },
        { field: 'name', title: '产品名称', width: 60 },
        { field: 'product_type', title: '产品分类', width: 40 ,align: 'left',
        formatter: function (value, row, index) {
            // console.log(row.product_type);
            var type;
            $.ajax({
                url:`${config.cateUrl}lists/${row.product_type}`,
                method: "get",
                async : false,
            }).then(res=>{
                if(res!=undefined){
                    // console.log(res.text);
                    type=res.text;
                }
            });
            return type;
        }
    },
        { field: 'keywords', title: '关键字', width: 70, align: 'left' },
        { field: 'buy_num', title: '销售数量', width: 40, align: 'left' },
        { field: 'price', title: '价格', width: 40, align: 'left' },
        {
            field: 'hot', title: '火热程度', width: 40, align: 'center',
            formatter: function (value, row, index) {
                //   console.log(row)
                if (row.sex) {
                    return '高';
                } else {
                    return '低';
                }
            }
        },
        { field: 'source', title: '地址', width: 100,align: 'left' },
        {
            field: 'pro_data', title: '发表日期', width: 80, align: 'center',
            formatter: function (value, row, index) {
                // console.log(row.pro_data);
                return moment(row.pro_data).utcOffset(480).format('YYYY-MM-DD HH:mm:ss');
            }
        },
        {
            field: 'manager', title: '操作', width: 100, align: 'center',
            formatter: function (value, row, index) {
                return `<a class="easyui-linkbutton" href="javascript:void(0);UpdataRow('${row._id}')">修改</a> <a class="easyui-linkbutton" href="javascript:void(0);DeleteRow('${row._id}')">删除</a> <a class="easyui-linkbutton" href="javascript:void(0);CommentRow('${row.product_type}')">评论</a>`;
            }
        }
    ]],
    view: detailview,
    detailFormatter: function (index, row) {
        return '<table>'+
                '<tr>' +
                '<td style="border:0">' +
                '<p>产品描述: ' + row.describe + '</p>' +
                '</td>' +
                '</tr>'+
                '<tr>' +
                '<td style="border:0">' +
                '<p>产品材质/材料: ' + row.parameter.material + '  产品适用人群:  ' + row.parameter.people + '</p>' +
                '</td>' +
                '</tr>'+
                '</table>';
    },
    toolbar: [{
        text: "添加产品数据",
        iconCls: 'icon-add',
        handler: function () {
            $('input[name=tab]').val("");
            $('#product_from').form('reset');
            var select = $('#tree').tree('getSelected');
            if (select != null) {
                $('#dialog').dialog("open");
            } else {
                $.messager.alert('Warning', '请选中分类');
            }
        }
    }, {
        text: "移除多个产品信息",
        iconCls: 'icon-help',
        handler: function () {
            //getSelections
            $.messager.confirm('Confirm', '您确定要删除选中数据吗?', function (r) {
                if (r) {
                    var select = $("#product").datagrid("getSelections");
                    var ids = [];
                    if (select.length > 0) {
                        for (let i = 0; i < select.length; i++) {
                            ids.push(select[i]._id);
                        }
                        $.ajax({
                            url: `${config.publicUrl}removes`,
                            method: "delete",
                            data: { ids: ids.toString() }//转出字符串
                        }).then(res => {
                            // console.log(res)
                            $('#product').datagrid('reload');
                        });
                    } else {
                        alert("对不起您还没有选中");
                    }
                }
            });
        }
    },
    {
        text: '查询数据',
        iconCls: 'icon-search',
        handler: function () {
            let ids = [];
            if($('#tree').tree('getSelected', 'getRoots')!=null){
                getlist(ids);
            }
            $("#product").datagrid({
                url: `${config.publicUrl}list`,
                method: "post",
                queryParams: {
                    search: $("input[name=search]").val(),
                    ids: ids.toString()
                }
            });
        }
    }],
    //数据加载成功以后渲染
    onLoadSuccess: function (data) {
        if (data.total == 0) {
            $(".datagrid-body:eq(1)").html('<p style="text-align:center;font-size:20px">对不起,获取不到数据</p>');
        }
        $("#searchtext").remove();
        var saerch = '<div id="searchtext"><input class="easyui-textbox" name="search" style="width:100px"></div> '
        $(".datagrid-toolbar>table td:eq(2)").before(saerch);
        $.parser.parse();
    }
});





//tip配置消息提示弹出框===》备用
$('#tip').dialog({
    title: '消息提示',
    width: 400,
    height: 200,
    closed: true,
    cache: false,
    modal: true
});


//window配置新增/修改窗口
$('#dialog').dialog({
    title: '数据修改/增加',
    width: 800,
    height: 550,
    closed: true,
    modal: true
});

$('#dialogs').dialog({
    title: '数据修改/增加',
    width: 700,
    height: 350,
    closed: true,
    modal: true
});



//提交表单数据(添加数据)
function submitForm() {
    $('#product_from').form('submit', {
        onSubmit: function () {
            if ($(this).form('enableValidation').form('validate')) {
                if ($('input[name=tab]').val() == "") {
                    const data = $('#product_from').serializeJSON();
                    //配置
                    data.parameter=JSON.stringify(data.parameter);
                    // data.product_type = $('#tree').tree('getSelected')._id;
                    data.hot = false;
                    data.buy_num = 0;
                    $.ajax({
                        url: `${config.publicUrl}create`,
                        method: "post",
                        data: data,
                        traditional: true, //默认false
                    }).then(res => {
                        console.log(res);
                        $('#dialog').dialog("close");
                        $('#product').datagrid('reload');
                    })
                } else {
                    const data = $('#product_from').serializeJSON();
                    data.parameter=JSON.stringify(data.parameter);
                    $.ajax({
                        url: `${config.publicUrl}update/${$('input[name=tab]').val()}`,
                        method: "put",
                        data: data,
                        traditional: true, //默认false
                    }).then(res => {
                        $('#dialog').dialog("close");
                        $('#product').datagrid('reload');
                    })
                }
            }
            return false;
        }
    });
}

//重置表单

function clearForm() {
    $('#product_from').form('clear');
}
function clearForms() {
    $('#comment_from').form('clear');
}


//修改单行数据
function UpdataRow(id) {
    $('input[name=tab]').val(id);
    $.ajax({
        url: `${config.publicUrl}list/${id}`,
        method: "get",
    }).then(res => {
        
        var special = {
            "keywords[]": res.keywords,
            "parameter[material]":res.parameter.material,
            "parameter[people]":res.parameter.people,
        }
        $('#product_from').form('load', res);
        $('#product_from').form('load', special);
    });
    $('#dialog').dialog("open");
}


//删除单行数据

function DeleteRow(id) {
    $.messager.confirm('Confirm', '您确定要删除该用户数据吗?', function (r) {
        if (r) {
            $.ajax({
                url: `${config.publicUrl}delete/${id}`,
                method: "delete",
            }).then(res => {
                $('#product').datagrid('reload');
                //  console.log(res);
            });
        }
    });
}


//初始化产品分类
function init() {
    //树
    $('#tree').tree({
        url: `${config.cateUrl}list/5d0b00328caec85a5898ce3c`,
        method: "get",
        animate: true,
    });

    //表单select
    $.ajax({
        url: `${config.cateUrl}list/5d0b00328caec85a5898ce3c`,
        method: "get",
    }).then(res=>{
        // console.log(res);
        let ids = [];
        getlists(res[0],ids);
        // console.log(ids);
        $("#product_type").combobox({
            valueField: 'text',
            textField: 'value',
            data: ids
        });
    });

    //表单select----评论
    $.ajax({
        url: `${config.cateUrl}lss/5d0ba59d74b3cb2fc814d894`,
        method: "get",
    }).then(res=>{
        // console.log(res);
        $("#type").combobox({
            valueField: '_id',
            textField: 'text',
            data: res,
        });
    });
}

init();



//选中树节点筛选
$("#tree").tree({
    onClick: function(node){
        // console.log(node);
        let ids = [];
        getlist(ids);
        // console.log(ids);
        //更新表格

        $('#product').datagrid({
            url: `${config.publicUrl}list`,
            method: "post",
            queryParams:{ids:ids.toString()}
        });
	}
})




//获取选中的子集
function getlist(ids){
    // let ids = [];
        let arr = $('#tree').tree('getSelected', 'getRoots');
        if (arr._id != undefined) {
            ids.push(arr._id);
        }
        //先判断是否有子目录
        if (arr.children != undefined) {
            xh(arr, ids);
        }

        //循环遍历所有子集
        function xh(child, arrs) {
            for (let i = 0; i < child.children.length; i++) {
                arrs.push(child.children[i]._id);
                if (child.children[i].children != undefined) {
                    // console.log(object);
                    xh(child.children[i], arrs);
                }
            }
        }
}


//获取选中的子集..=====>设置拉选select
function getlists(arr,ids){
    // let ids = [];
        if (arr._id != undefined) {
            ids.push({"value":arr.text,"text":arr._id});
        }
        //先判断是否有子目录
        if (arr.children != undefined) {
            xh(arr, ids);
        }

        //循环遍历所有子集
        function xh(child, arrs) {
            for (let i = 0; i < child.children.length; i++) {
                ids.push({"value":child.children[i].text,"text":child.children[i]._id});
                // arrs.push(child.children[i]._id);
                if (child.children[i].children != undefined) {
                    // console.log(object);
                    xh(child.children[i], arrs);
                }
            }
        }
}


//评论功能
function CommentRow(id){
    $('input[name=tab]').val(id)
    $('#dialogs').dialog("open");
}

//提交评论
function submitForms() {
    $('#comment_from').form('submit', {
        onSubmit: function () {
            if ($(this).form('enableValidation').form('validate')) {
                // console.log("object");
                const data = $('#comment_from').serializeJSON();
                    //配置
                    data.person_name=getCookie(window.localStorage.getItem("keys"));
                    data.modules_type=$('input[name=tab]').val();
                    data.status = false;
                    data.good = 0;
                    $.ajax({
                        url: `${config.commentUrl}create`,
                        method: "post",
                        data: data,
                        traditional: true, //默认false
                    }).then(res => {
                        // console.log(res);
                        $('#dialogs').dialog("close");
                    })
            }
        }
    })
}


//获取cookie
function getCookie(c_name) {
    if (document.cookie.length > 0) {
      c_start = document.cookie.indexOf(c_name + "=")
      if (c_start != -1) {
        c_start = c_start + c_name.length + 1
        c_end = document.cookie.indexOf(";", c_start)
        if (c_end == -1) c_end = document.cookie.length
        return unescape(document.cookie.substring(c_start, c_end))
      }
    }
    return ""
  }